package com.devunion.salon.persistence.dao;

import com.devunion.salon.persistence.Service;
import com.devunion.salon.persistence.Service2Employee;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Viktar Liaskovich
 */
public class Service2EmployeeDao extends BaseDaoObject<Service2Employee> {
    public Service2Employee getByKey(Serializable key) {
        return (Service2Employee) getHibernateTemplate().get(Service2Employee.class, key);
    }

    public Set<Service> getEmployeeServices(final Serializable key) {
        return (Set<Service>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                List<Service> result = session.createQuery("select s2e.service from Service2Employee s2e where " +
                        "s2e.employee.id = :emplKey")
                        .setParameter("emplKey", key, Hibernate.LONG)
                        .list();

                return result == null || result.isEmpty() ? new HashSet<Service>() : new HashSet<Service>(result);
            }
        });
    }
}